/**
 * http://www.koorz.com
 * Copyright (c) 2012 shanghai meiku information technology co,.ltd
 */
package com.koorz.modules.search.hichao;

import java.util.concurrent.CountDownLatch;

import org.apache.commons.lang.StringUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.log.Logger;
import com.koorz.modules.crawl.CrawlHistory;
import com.koorz.modules.image.Image;
import com.koorz.modules.search.SimpleHttpClient;
import com.koorz.modules.search.TaskService;
import com.koorz.modules.search.ThreadPoolMananger;
import com.koorz.modules.search.UrlWrapper;
import com.koorz.modules.style.SimilarItems;
import com.koorz.modules.style.Style;
import com.koorz.modules.style.StyleItems;
import com.koorz.modules.user.User;
import com.koorz.utils.DateUtil;


/**
 * 功能描述：搭配任务
 * 作        者：尹东东 
 * 创建时间：2013-5-27 下午3:58:57
 * 版  本  号：1.0
 */
public class StyleTask implements Runnable{
	protected final Logger logger = Logger.getLogger(getClass());
	private final CountDownLatch stopSignal;
	
	public StyleTask(CountDownLatch start){
		stopSignal = start;
	}
	@Override
	public void run() {
		logger.debug("进入StyleTask，等待导航初始化完成");
		try {
			stopSignal.await();
		} catch (InterruptedException e1) {
			e1.printStackTrace();
		}
		logger.debug("进入StyleTask，导航初始化完成");
		
		HichaoParser parser = HichaoParser.getInstance();
		while (true) {
			if(parser.isStopCrawl()){
				logger.debug("StyleTask 导航链接抓取完成");
				break;
			}
			UrlWrapper navi = parser.getNavi();
			if(navi != null){
				CrawlHistory crawl = CrawlHistory.dao.findFirst("select * from crawl_history where url=?", navi.getUrl());
				if(crawl != null){
					continue;
				}
				logger.debug("进入StyleTask  while");
				SimpleHttpClient client = new SimpleHttpClient();
				String result = client.get(navi.getUrl(),parser.getCookie());
				JSONObject data = null;
				JSONArray jsonArray = null;
				try {
					JSONObject json = JSON.parseObject(result);
					data = json.getJSONObject("data");
					jsonArray = data.getJSONArray("related_items");
				} catch (Exception e) {
					e.printStackTrace();
					logger.error("StyleTask 单品搭配队列请求数据失败！"+navi.getUrl()+"  --  "+navi.getLabel(), e);
					continue;
				}
				TaskService taskService = TaskService.getInstance();
				User user = new User();
				user.set("nickname", data.getString("username"));
				user.set("gender", User.Gender.UNKNOWN.ordinal());
				user.set("avatar_large", data.getString("user_url"));
				user.set("avatar", data.getString("user_url"));
				user.set("score", "0");
				user.set("online", "0");
				user = taskService.saveUser(user);
				
				///下载用户头像
				try {
					parser.pushQueue();
					ThreadPoolMananger.ImageQueue.put(user);
				} catch (InterruptedException e) {
					e.printStackTrace();
					logger.error("StyleTask 添加图片队列--user 失败！", e);
				}
				//保存主图
				Image image = new Image();
				image.set("description", data.getString("description"));
				//http://img.haobao.com/images/imageshttp://img01.taobaocdn.com/bao/uploaded/i1/263817957/T2kIGbXkhXXXXXXXXX_!!263817957.jpg
				String url = data.getString("url");
				if(StringUtils.contains(url, "taobaocdn.com")){
					url = StringUtils.substringAfterLast(url, "http://img.haobao.com/images/images");
				}
				image.set("url", url);
				image.set("check_state", Image.ImageState.SHOW.ordinal());
				image.set("check_time", DateUtil.getNowDateTime());
				image.set("type", Image.ImageType.STAR.ordinal());
				image.set("source_id", data.getString("id"));
				image.set("user_id", user.getStr("id"));
				image = taskService.saveImage(image);
				///下载主图图片
				try {
					parser.pushQueue();
					ThreadPoolMananger.ImageQueue.put(image);
				} catch (InterruptedException e) {
					e.printStackTrace();
					logger.error("StyleTask 添加图片队列--image 失败！", e);
				}
				taskService.addImageToCategory(image.getStr("id"), navi.getCategoryId());
				taskService.addImageToLabel(image.getStr("id"), navi.getLabel());
				taskService.addImageToLabelGroup(image.getStr("id"), navi.getLabelGroupId());
				
				//创建主图搭配
				Style style = new Style();
				style.set("image_id", image.getStr("id"));
				style.set("check_state", Style.StyleState.SHOW.ordinal());
				style.set("check_time", DateUtil.getNowDateTime());
				style.set("user_id", user.getStr("id"));
				style.set("description", data.getString("description"));
				style = taskService.addStyle(style);
				//搭配项序号
				int index = 1;
				for(int i=0;i<jsonArray.size();i++){
					JSONObject json = jsonArray.getJSONObject(i);
					String name = json.getString("name");
					String categoryId = "";
					String label = "";
					String labelGroupId = "";
					//将搭配归类入数据库
					if(name.equals("shangyi")){
						categoryId = "100000";
						label = navi.getLabel();
						labelGroupId = "100093";
					}else if(name.equals("waitao")){
						categoryId = "100000";
						label = navi.getLabel();
						labelGroupId = "100094";
					}else if(name.equals("ku")){
						categoryId = "100000";
						label = navi.getLabel();
						labelGroupId = "100089";
					}else if(name.equals("lianyiqun")){
						categoryId = "100000";
						label = navi.getLabel();
						labelGroupId = "100091";
					}else if(name.equals("qun")){
						categoryId = "100000";
						label = navi.getLabel();
						labelGroupId = "100091";
					}else if(name.equals("xie")){
						categoryId = "100001";
						label = navi.getLabel();
					}else if(name.equals("bao")){
						categoryId = "100002";
						label = navi.getLabel();
					}else {
						//peishi
						categoryId = "100003";
						label = navi.getLabel();
					}
					JSONArray itemsArray = json.getJSONArray("items");
					StyleItems styleItem = null;
					for(int j=0;j<itemsArray.size();j++){
						JSONObject itemObj = itemsArray.getJSONObject(j);
						
						Image item = new Image();
						item.set("description", itemObj.getString("title"));
						item.set("url", itemObj.getString("url"));
						item.set("check_state", Image.ImageState.SHOW.ordinal());
						item.set("check_time", DateUtil.getNowDateTime());
						item.set("type", Image.ImageType.SINGLE.ordinal());
						item.set("source_id", itemObj.getString("source_id"));
						item.set("source", itemObj.getString("source"));
						item.set("price", itemObj.getDouble("price"));
						item.set("goods_link", itemObj.getString("link"));
						item.set("user_id", user.getStr("id"));
						item = taskService.saveImage(item);
						
						taskService.addImageToCategory(item.getStr("id"), categoryId);
						taskService.addImageToLabel(item.getStr("id"), label);
						if(!StringUtils.isEmpty(labelGroupId)){
							taskService.addImageToLabelGroup(item.getStr("id"), labelGroupId);
						}
						
						//只在第一个单品保存成搭配项
						if(j == 0){
							styleItem = new StyleItems();
							styleItem.set("style_id", style.getStr("id"));
							styleItem.set("image_id", item.getStr("id"));
							styleItem.set("sequence", index);
							taskService.addStyleItems(styleItem);
							index++;
						}
						//保存单品相似项
						SimilarItems similarItem = new SimilarItems();
						similarItem.set("image_id", styleItem.getStr("image_id"));
						similarItem.set("item_id", item.getStr("id"));
						similarItem.set("sequence", j+1);
						taskService.addSimilarItems(similarItem);
						
						///下载单品图片
						try {
							parser.pushQueue();
							ThreadPoolMananger.ImageQueue.put(item);
						} catch (InterruptedException e) {
							e.printStackTrace();
							logger.error("StyleTask 添加图片队列--item 失败！", e);
						}
					}
				}
				CrawlHistory crawlH = new CrawlHistory();
				crawlH.set("website", "http://www.hichao.com");
				crawlH.set("url", navi.getUrl());
				taskService.addCrawlHistory(crawlH);
				parser.setCrawlCount();
				client.close();
			}
		}
	}

}
